﻿using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;

namespace BuildServer.Models
{
    public class BuildDefinition
    {
        [Key]
        public int Id { get; set; }

        [Required(ErrorMessage = "Name is required")]
        [Display(Name = "Name")]
        public string Name { get; set; }

        [Display(Name = "Nightly")]
        public bool IsNightly { get; set; }

        [Required(ErrorMessage = "Build Template is required")]
        [Column("BuildTemplate_Id")]
        public int BuildTemplateId { get; set; }

        [Display(Name = "Build Template")]
        [ForeignKey("BuildTemplateId")]
        public virtual BuildTemplate BuildTemplate { get; set; }

        /// <summary>
        /// Gets the build properties for this build definition
        /// </summary>
        public virtual ICollection<BuildProperty> BuildProperties { get; set; }

        /// <summary>
        /// Gets the build run for this build definition
        /// </summary>
        public virtual ICollection<BuildRun> BuildRuns { get; set; }

        /// <summary>
        /// Gets the build definition name without invalid path characters
        /// </summary>
        public string BuildLabel
        {
            get
            {
                return string.Join(string.Empty, Name.Split(System.IO.Path.GetInvalidPathChars()));
            }
        }

        public string GetBuildProperty(string name)
        {
            switch (name)
            {
                case "Name":
                    return this.Name;
                case "build_label":
                    return this.BuildLabel;
                default:
                    var buildProperty = BuildProperties.FirstOrDefault(x => x.Name == name);
                    return (buildProperty == null) ? null : buildProperty.Value;
            }
        }

        public void SetBuildProperty(string name, string value)
        {
            switch (name)
            {
                case "Name":
                case "build_label":
                    return;
            }

            var buildProperty = BuildProperties.FirstOrDefault(x => x.Name == name);
            if (buildProperty == null)
            {
                BuildProperties.Add(new BuildProperty { Name = name, Value = value });
            }
            else
            {
                buildProperty.Value = value;
            }
        }
    }
}